<template>
  <div class="search-form">
    <el-row
      type="flex"
      :gutter="12"
    >
      <el-col
        v-for="(item, index) in lists"
        :key="index"
        :xs="8"
        :sm="8"
        :md="6"
        :lg="4"
        :xl="4"
        style="padding-bottom: 12px"
      >
        <!-- 输入框 -->
        <el-input
          v-if="item.type === 'input'"
          v-model:value="mainForm[item.field]"
          :placeholder="item.placeholder"
        />
        <!-- 数字框 -->
        <el-input
          v-if="item.type === 'number'"
          v-model:value="mainForm[item.field]"
          type="number"
          :placeholder="item.placeholder"
          style="width: 100%"
        />
        <!-- 下拉框 -->
        <el-select
          v-if="item.type === 'select'"
          v-model:value="mainForm[item.field]"
          style="width: 100%"
          :placeholder="item.placeholder"
        >
          <el-option
            v-for="option in item.options"
            :key="option.code"
            :value="option.code"
            :label="option.label"
          />
        </el-select>
        <!-- 日期选择器 -->
        <el-date-picker
          v-if="item.type === 'date'"
          v-model:value="mainForm[item.field]"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="item.placeholder"
          style="width: 100%"
        />
        <template v-if="item.type === 'actions'">
          <el-button
            v-for="(list, indexa) in item.buttons"
            :key="indexa"
            v-bind="list"
            @click="handleClick(list)"
          >
            {{ list.text }}</el-button>
        </template>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive } from 'vue'

defineOptions({
  name: 'SearchForms'
})

const props = defineProps({
  lists: {
    type: Array,
    default: () => [],
  },
})
const emit = defineEmits(['search', 'reset'])
// 初始化数据
const originalData = props.lists
  .filter((item) => item.type !== 'actions')
  .reduce((a, b) => {
    a[b.field] = undefined
    return a
  }, {})
const mainForm = reactive({ ...originalData })
const handleClick = ({ clickType }) => {
  switch (clickType) {
    // 搜索
    case 1:
      emit('search', mainForm)
      break
      // 重置
    case 2:
      emit('reset')
      resetState(mainForm, originalData)
      break
      // 导出
    case 3:
      emit('export')
      resetState(mainForm, originalData)
      break
    default:
      ''
  }
  emit('')
}

// 重置
const resetState = (state, originalData) => {
  Object.assign(state, originalData)
}
</script>

<style lang="scss" scoped></style>
